package com.lant.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.Random;

import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

public class PdfUtils {
	private static Logger logger = LoggerFactory.getLogger(PdfUtils.class);

	private PdfUtils() {
		super();
	}

	public static void createPdfByHtmlFile(String outputPDFFile, String inputHTMLFileName)
			throws IOException, DocumentException, ParserConfigurationException, SAXException {
		StringBuilder content = new StringBuilder();

		try (BufferedReader reader = new BufferedReader(new FileReader(new File(inputHTMLFileName)));) {
			String line = null;

			while ((line = reader.readLine()) != null) {
				line = line.replace("&nbsp;", " ");
				content.append(line).append("\r\n");
			}
		} catch (Exception e) {
			logger.error("创建pdf异常", e);
		}

		createPDFByContent(outputPDFFile, content.toString());
	}

	public static void createPDFByContent(String outputPDFFile, String content)
			throws IOException, DocumentException, ParserConfigurationException, SAXException {
		InputSource is = new InputSource(new BufferedReader(new StringReader(content)));
		Document document = XMLResource.load(is).getDocument();

		ITextRenderer renderer = new ITextRenderer();
		ITextFontResolver font = renderer.getFontResolver();
		// 改变不同系统上的字体路径
		if (System.getProperties().getProperty("os.name").toLowerCase().contains("windows")) {
			font.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		} else {
			font.addFont("/usr/share/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		}

		OutputStream os = new FileOutputStream(outputPDFFile);
		renderer.setDocument(document, null);
		renderer.layout();
		renderer.createPDF(os);
		os.close();
	}

	/**
	 * 生成合同编号 当前时间+3位数字随机码
	 * 
	 * @return
	 */
	public static String getRandomCode() {
		String temp = "";
		String randomCode = "";
		Random random = new Random();
		String[] arr = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

		while (randomCode.length() < 3) {
			temp = arr[random.nextInt(10)];

			if (randomCode.indexOf(temp) == -1) {
				randomCode += temp;
			}
		}

		return System.currentTimeMillis() + randomCode;
	}

}